package com.zl.test.restdemo.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.SQLOutput;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: zhang lei
 * @Describe: All things are difficult before they are easy.
 * @CreatTime: 2021-03-11-23-55
 */
@ServerEndpoint(value = "/webTest")
@Component
public class MyWebSocket {
    /**
     * @ServerEndpoint(value = "/webTest") 前端通过此 URI 和后端交互，建立连接
     * @Component 不用说将此类交给 spring 管理
     * @OnOpen websocket 建立连接的注解，前端触发上面 URI 时会进入此注解标注的方法，和之前关于 DWR 文章中的 onpage 方法类似
     * @OnClose 顾名思义关闭连接，销毁 session
     * @OnMessage 收到前端传来的消息后执行的方法
     */
    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<MyWebSocket> webSockets = new CopyOnWriteArraySet<MyWebSocket>();
    private Session session;

    //建立连接的注解
    @OnOpen
    public void  onOpen(Session session){
        this.session = session;
        webSockets.add(this);
        addOnlineCount();
        System.out.println("有新连接加入！当前在线人数为"+getOnlineCount());
        try {
            sendMassage("连接建立成功");
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    @OnClose
    public void  onClone(){
        webSockets.remove(this);
        subOnlineCount();
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("来自客户端的消息"+message);
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();;

    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }


    public  void sendMassage(String message)throws IOException  {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void setOnlineCount(int onlineCount) {
        MyWebSocket.onlineCount = onlineCount;
    }

    public static CopyOnWriteArraySet<MyWebSocket> getWebSockets() {
        return webSockets;
    }

    public static void setWebSockets(CopyOnWriteArraySet<MyWebSocket> webSockets) {
        MyWebSocket.webSockets = webSockets;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }
}
